﻿#include "UtilNetWork.h"

bool UtilNetWork::isNetOnline()
{
    //检测操作系统是否能连通外部链接
#ifdef _WIN32
    bool bol = false; //是否联网,联网 true,不联网 false
    CoInitialize(NULL);
    //  通过NLA接口获取网络状态
    IUnknown *pUnknown = NULL;
    HRESULT Result = CoCreateInstance(CLSID_NetworkListManager, NULL, CLSCTX_ALL, IID_IUnknown, (void **)&pUnknown);
    if (SUCCEEDED(Result))
    {
        INetworkListManager *pNetworkListManager = NULL;
        if (pUnknown)
            Result = pUnknown->QueryInterface(IID_INetworkListManager, (void **)&pNetworkListManager);
        if (SUCCEEDED(Result))
        {
            VARIANT_BOOL IsConnect = VARIANT_FALSE;
            if (pNetworkListManager)
                Result = pNetworkListManager->get_IsConnectedToInternet(&IsConnect);
            if (SUCCEEDED(Result))
            {
                bol = (IsConnect == VARIANT_TRUE) ? true : false;
            }
        }
        if (pNetworkListManager)
            pNetworkListManager->Release();
    }
    if (pUnknown)
        pUnknown->Release();
    CoUninitialize();
    return bol;
#else
    bool flag = false;
    char ip[100] = {0};
    QVector<const char *> t_Hostname;
    t_Hostname.push_back("www.baidu.com");
    t_Hostname.push_back("www.163.com");
    t_Hostname.push_back("www.qq.com");
    for (int i = 0;i < t_Hostname.size();++i)
    {
        struct hostent *he;
        struct in_addr **addr_list;
        if ((he = gethostbyname(t_Hostname[i])) == nullptr)
        {
            flag = false;
        }
        else
        {
            addr_list = (struct in_addr **)he->h_addr_list;
            for (i = 0; addr_list[i] != nullptr; i++)
            {
                strcpy(ip, inet_ntoa(*addr_list[i]));
                flag = true;
                break;
            }
            break;
        }
    }
    return flag;
#endif
}
